<template>
  <el-container>
    <el-header>我的</el-header>
    <el-main>
      <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="昵称" prop="nickName">
          <el-input v-model="ruleForm.nickName"></el-input>
        </el-form-item>
        <el-form-item label="头像" prop="age">
          <!-- <el-input v-model.number="ruleForm.age"></el-input> -->
          <el-upload name="imgfile" drag class="upload-img" action="" :http-request="uploadImg" :show-file-list="false"
            :on-success="handleAvatarSuccess">
            <img v-if="ruleForm.img" :src="ruleForm.img" class="avatar" />
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">修改</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>

          <el-button @click="updatePwd">修改密码</el-button>
          
          <el-button @click="editLogin">退出登录</el-button>
        </el-form-item>
      </el-form>

      <!-- 修改密码弹窗 -->
      <el-dialog title="修改密码" :visible.sync="editPwdDialogVisible" width="80%" :before-close="handleCloseAddRoomDialog">
        <el-form :model="editPwdForm" status-icon :rules="editPwdRules" ref="editPwdForm" label-width="100px" class="editPwdFormDemo">
          <el-form-item label="新密码" prop="newpassword">
            <el-input type="password" v-model="editPwdForm.newpassword"></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="checkpassword">
            <el-input type="password" v-model="editPwdForm.checkpassword"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitEditPwdForm()">提交</el-button>
            <el-button @click="resetEditPwdForm">重置</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </el-main>
    <el-footer>
      <el-row type="flex" class="row-bg">
        <el-col :span="12">
          <div class="grid-content bg-purple div-msg"><a class="btn1" v-on:click="goHome()">聊天室</a></div>
        </el-col>
        <el-col :span="12">
          <div class="grid-content bg-purple div-self"><a class="btn2">我的</a></div>
        </el-col>
      </el-row>
    </el-footer>
  </el-container>
</template>

<script>
  import {
    checkResData,
    getToken,
    getUserId,
    clearAllCookie
  } from '../utils/selfInfoUtil.js'
  export default {
    name: 'Self',
    data() {
      var checkpassword = (rule, value, callback) => {
        if (value !== this.editPwdForm.newpassword.trim()) {
          return callback(new Error("两次输入密码不一致"))
        }
        return callback()
      };
      return {
        editPwdDialogVisible: false,
        editPwdForm: {
          newpassword: '',
          checkpassword: ''
        },
        ruleForm: {
          nickName: '',
          img: ''
        },
        editPwdRules: {
          newpassword: [{
            required: true,
            message: "请输入确认密码",
            trigger: "change"
          }, {
            min: 6,
            max: 16,
            message: "密码长度为 6 - 16 字符",
            trigger: "change"
          }],
          checkpassword: [{
            required: true,
            validator: checkpassword,
            trigger: "change"
          }]
        },
        rules: {
          nickName: [{
              required: true,
              message: "请输入用户昵称",
              trigger: "change"
            },
            {
              min: 2,
              max: 20,
              message: "长度在2-20个字符",
              trigger: "change"
            }
          ]
        }
      }
    },
    created() {
      this.getUserInfo()
    },
    methods: {
      submitForm(ruleForm) {
        this.$refs[ruleForm].validate((valid) => {
          if (valid) {
            this.$axios.post('user/update', {
                id: getUserId(),
                nickname: this.ruleForm.nickName,
                img: this.ruleForm.img
              }).then(res => {
                if (checkResData(res.data.code, res.data.success)) {
                  this.$message.success(res.data.msg)
                } else {
                  this.$message.info(res.data.msg)
                }
              })
              .catch(err => {
                this.$message.error("服务器溜了！ 已经去抓了")
              })
          } else {
            return false;
          }
        });
      },
      // 更新密码操作
      submitEditPwdForm() {
        this.$refs.editPwdForm.validate((valid) => {
          if (valid) {
            this.$axios.post('user/update', {
                id: getUserId(),
                password: this.editPwdForm.checkpassword
              })
              .then(res => {
                console.log(res)
                if (checkResData(res.data.code, res.data.success)) {
                  this.$message.success(res.data.msg)
                  // 退出当前登录
                  clearAllCookie()
                  this.$router.push(`login`)
                } else {
                  this.$message.info(res.data.msg)
                }
              })
              .catch(err => {
                this.$message.error("服务器溜了！ 已经去抓了")
              })
          } else {
            return false;
          }
        });
      },
      resetEditPwdForm() {
        this.$refs.editPwdForm.resetFields();
      },
      resetForm(ruleForm) {
        this.$refs[ruleForm].resetFields();
        this.ruleForm.img = ''
      },
      // 上传用户头像
      uploadImg(data) {
        const formData = new FormData();
        formData.append("file", data.file)
        this.$axios.post('file/uploadfile', formData, {
            headers: {
              "Content-Type": "multipart/form-data",
              "TOKEN": getToken()
            }
          })
          .then(res => {
            data.onSuccess(res, data.file)
          })
          .catch(err => {
            data.onError(err)
          })
      },
      // 图片上传成功
      handleAvatarSuccess(res, file) {
        this.ruleForm.img = res.data.data;
        this.$message.success("图片上传成功!");
      },
      // 获取当前用户基本信息
      getUserInfo() {
        this.$axios.post('user/getUserInfo')
          .then(res => {
            if (checkResData(res.data.code, res.data.success)) {
              this.ruleForm.img = res.data.data.img
              this.ruleForm.nickName = res.data.data.nickname
            } else {
              this.$message.info(res.data.msg)
            }
          })
          .catch(err => {
            this.$message.error("服务器溜了！ 已经去抓了")
          })
      },
      // 密码修改
      updatePwd() {
        this.editPwdDialogVisible = true
      },
      handleCloseAddRoomDialog(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
      },
      goHome() {
        this.$router.push(`home`)
      },
      // 退出当前登录
      editLogin() {
        clearAllCookie()
        this.$router.push(`login`)
      }
    }
  }
</script>

<style scoped="scoped">
  .el-footer,
  .el-header {
    text-align: center;
    background-color: #B3C0D1;
    color: #333;
    line-height: 3.75rem;
  }

  .el-main {
    background-color: #E9EEF3;
    color: #333;
  }

  .el-container {
    padding: 0;
    margin: 0;
    min-height: 100vh;
    background-color: #0077AA;
  }

  .div-self {
    color: #158bb8;
    font-size: 1.125rem;
  }

  .div-msg {
    color: white;
    font-size: 100%;
  }

  .btn1,
  .btn2 {
    cursor: pointer;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  .box {
    position: relative;
    width: 10rem;
    height: 10rem;
    margin: 2rem auto;
    box-shadow: 0 14px 28px rgba(0, 0, 0, 0.25), 0 10px 10px rgba(0, 0, 0, 0.22);
  }
</style>
